<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="商品分类列表"
      row-key="id"
      :indent="20"
      :columns="columns"
      :request-api="getProductCategoryList"
      :data-callback="dataCallback"
    >
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增分类 </el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteCategory(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <CategoryDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx" name="category">
import { ref } from "vue";
import { Product } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import {
  getProductCategoryList,
  addProductCategory,
  editProductCategory,
  deleteProductCategory,
  changeCategoryShow
} from "@/api/modules/product";
import CategoryDrawer from "@/views/product/components/CategoryDrawer.vue";
import { CirclePlus, EditPen, Delete } from "@element-plus/icons-vue";

const dataCallback = (data: any) => {
  return {
    list: data,
    total: 20,
    page: 1,
    limit: 20
  };
};
const proTable = ref<ProTableInstance>();

const columns: ColumnProps<Product.ResCategoryList>[] = [
  { prop: "name", label: "分类名称", align: "left", search: { el: "input" } },
  {
    prop: "isShow",
    label: "是否显示",
    align: "right",
    fieldNames: { label: "label", value: "status" },
    render: scope => {
      return (
        <el-switch
          model-value={scope.row.isShow}
          active-text={scope.row.isShow ? "开启" : "关闭"}
          active-value={true}
          inactive-value={false}
          onClick={() => changeStatus(scope.row)}
        />
      );
    }
  },
  { prop: "operation", label: "操作", width: 220, fixed: "right" }
];

// 切换分类显示状态
const changeStatus = async (row: Product.ResCategoryList) => {
  await useHandleData(changeCategoryShow, { id: row.id, data: row.isShow == true ? false : true }, `切换【${row.name}】显示状态`);
  proTable.value?.getTableList();
};

const deleteCategory = async (params: Product.ResCategoryList) => {
  await useHandleData(deleteProductCategory, { id: params.id }, `删除【${params.name}】品牌`);
  proTable.value?.getTableList();
};

const drawerRef = ref<InstanceType<typeof CategoryDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Product.ResCategoryList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: title === "查看",
    api: title === "新增" ? addProductCategory : title === "编辑" ? editProductCategory : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
